# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_ningde_class_policy'

    province = '福建省'
    city = '宁德市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 5,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521, 403],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": None,
                #     "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": None,
                #     # **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, channelid, classsql in [
            ["宁德市工业和信息化局", "", "https://gxj.ningde.gov.cn/xxgk/zfxxgkzl/zc/gfxwj01/", "202878", "chnlid=55568*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市科学技术局", "", "https://kjj.ningde.gov.cn/zwgk/zc/gfxwj/", "202046", "chnlid=52748*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市财政局", "", "https://czj.ningde.gov.cn/zfxxgk/zc/xzgfxwj/", "203674", "chnlid=56991*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市人力资源和社会保障局", "", "https://rsj.ningde.gov.cn/xxgk/zc/gfxwj/", "203106", "chnlid=52696*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市自然资源局", "", "https://zrzyj.ningde.gov.cn/zfxxgk/zc/gfxwj/", "200493", "chnlid=52720*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市住房和城乡建设局", "", "https://zjj.ningde.gov.cn/xxgkzl/zc/gfxwj/", "297104", "chnlid=52770*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市农业农村局", "", "https://nyncj.ningde.gov.cn/zwgk/zfxxgkzl/zc/gfxwj/", "204251", "chnlid=52740*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市商务局", "", "https://swj.ningde.gov.cn/zfxxgkzl/zc/gfxwj/", "203388", "chnlid=52763*efftype='01'*fileinfotype='行政规范性文件'"],
            ["宁德市市场监督管理局", "", "https://scjd.ningde.gov.cn/zw/zfxxgkzl/zca/xzgfxwj/", "202959", "chnlid=57006,53302*efftype='01'*fileinfotype='行政规范性文件'"],
        ]:
            data = {
                'sortfield': '-pubdate',
                'channelid': channelid,
                'classsql': classsql,
                'classnum': str(100),
                'classsort': str(0),
                # 'cache': True,
                'prepage': str(75),
                'page': str(1),
            }
            temp_url = urljoin(url, '/fjdzapp/search')
            meta = {"item": {'source': source, 'county': county}}
            meta.update({
                "data": data,
            })
            print(data)
            yield self.FormRequest(
                temp_url,
                formdata=data,
                method="POST",
                callback=self.parse_list,
                dont_filter=True,
                meta=meta
            )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        url_list = response.json()['data']
        for elem in url_list:
            item = Item()
            item['source_url'] = elem['chnldocurl']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubdate'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(item['publish_date'], response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_page = int(response.json()['pageCount'])
        print(meta['data'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1)):
            data = meta.get("data")
            data['page'] = str(page)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {data}")
            yield self.FormRequest(
                response.url,
                formdata=meta['data'],
                method="POST",
                meta=meta,
                callback=self.parse_list,
                dont_filter=True
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_ningde_class_policy -a get_next=0".split())
